<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 被观察者
    //    状态
    //    观察者队列
    //    添加观察者
    //    移除观察者
    // 观察者
    //    姓名
    //    事件
    class Observer {
      constructor({ name, callback }) {
        this.name = name;
        this.callback = callback
      }
    }

    class Observered {
      constructor() {
        this.observers = [];
        this.state = '学习'
      }
      add(observer) {
        if (this.observers.find(item => item === observer)) return
        this.observers.push(observer)
      }
      setState(state) {
        this.state = state
        this.observers.forEach(item => {
          item.callback(state)
        })
      }
      remove(observer) {
        this.observers = this.observers.filter(item => item !== observer)
      }
    }

    const dx = new Observer({
      name: 'dx',
      callback: (state) => {
        console.log('上违纪' + state)
      }
    })
    const fdy = new Observer({
      name: 'fdy',
      callback: (state) => {
        console.log('找你谈话' + state)
      }
    })
    const sjx = new Observered()
    sjx.add(dx)
    sjx.add(fdy)
    sjx.add(dx)
    setTimeout(() => {
      sjx.setState('睡觉')
    }, 1000)

    setTimeout(() => {
      sjx.remove(dx)
    }, 3000)

    setTimeout(() => {
      sjx.setState('玩游戏')
    }, 4000)
    console.log(dx, fdy, sjx)
  </script>
</body>

</html>